<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
      <el-form-item label="菜单名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入菜单名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="菜单状态" clearable size="small">
          <el-option
            v-for="(data,index) in statusOptions"
            :key="index"
            :label="data.label"
            :value="data.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-has-permi="['user:menu:add']"
        >新增
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="fetchNodeList"></right-toolbar>
    </el-row>
    <el-table
      :data="menuList"
      style="width: 100%;margin-bottom: 20px;"
      row-key="id"
      border
      v-loading="loading"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column
        prop="name"
        label="名称"
        sortable
        width="180">
      </el-table-column>
      <el-table-column prop="icon" label="图标" align="center" width="100">
        <template slot-scope="scope" v-if="scope.row.icon !== null">
          <svg-icon :icon-class="scope.row.icon"/>
        </template>
      </el-table-column>
      <el-table-column
        prop="path"
        label="访问路径"
        sortable
        width="180">
      </el-table-column>
      <el-table-column
        prop="component"
        label="组件路径"
        sortable
        width="180">
      </el-table-column>
      <el-table-column
        prop="permissionValue"
        label="权限值">
      </el-table-column>
      <el-table-column prop="status" label="状态" :formatter="statusFormat" width="80"></el-table-column>
      <el-table-column label="创建时间" align="center" prop="gmtCreate">
        <template slot-scope="scope">
          <span>{{ scope.row.gmtCreate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-has-permi="['user:menu:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-has-permi="['user:menu:add']"
          >新增
          </el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-has-permi="['user:menu:delete']"
          >删除
          </el-button>

        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改菜单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级菜单">
              <tree-select
                v-model="form.pid"
                :options="menuOptions"
                :normalizer="normalizer"
                :show-count="true"
                placeholder="选择上级菜单"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="菜单类型" prop="type">
              <el-radio-group v-model="form.type">
                <el-radio :label="1">目录</el-radio>
                <el-radio :label="2">菜单</el-radio>
                <el-radio :label="3">按钮</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item v-if="form.type !== 3" label="菜单图标">
              <el-popover
                placement="bottom-start"
                width="460"
                trigger="click"
                @show="$refs['iconSelect'].reset()"
              >
                <IconSelect ref="iconSelect" @selected="selected"/>
                <el-input slot="reference" v-model="form.icon" placeholder="点击选择图标" readonly>
                  <svg-icon
                    v-if="form.icon"
                    slot="prefix"
                    :icon-class="form.icon"
                    class="el-input__icon"
                    style="height: 32px;width: 16px;"
                  />
                  <i v-else slot="prefix" class="el-icon-search el-input__icon"/>
                </el-input>
              </el-popover>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入菜单名称"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item v-if="form.type !== 3" label="是否外链">
              <el-radio-group v-model="form.isOutChain">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.type !== 3" label="路由地址" prop="path">
              <el-input v-model="form.path" placeholder="请输入路由地址"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" v-if="form.type === 2">
            <el-form-item label="组件路径" prop="component">
              <el-input v-model="form.component" placeholder="请输入组件路径"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.type !== 1" label="权限标识">
              <el-input v-model="form.permissionValue" placeholder="请输入权限标识" maxlength="50"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item v-if="form.type !== 3" label="显示状态">
              <el-radio-group v-model="form.hidden">
                <el-radio
                  v-for="(data,index) in visibleOptions"
                  :key="index"
                  :label="data.value"
                  :value="data.value"
                >{{ data.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.type !== 3" label="菜单状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="(data,index) in statusOptions"
                  :key="index"
                  :label="data.value"
                >{{ data.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import menu from '@/api/user/menu'
  import TreeSelect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import IconSelect from "@/components/IconSelect";
  import { statusOptions, visibleOptions } from "@/utils/feige";

  export default {
    name: 'Menu',
    components: {TreeSelect, IconSelect},
    data() {
      return {
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        // 遮罩层
        loading: true,
        // 显示搜索条件
        showSearch: true,
        // 查询参数
        queryParams: {
          name: undefined,
          status: undefined
        },
        // 菜单表格树数据
        menuList: [],
        // 菜单树选项
        menuOptions: [],
        // 弹出层标题
        title: "添加菜单",
        // 是否显示弹出层
        open: false,
        //表单数据
        form: {},
        visibleOptions: visibleOptions,
        statusOptions: statusOptions,
        // 表单校验
        rules: {
          name: [
            {required: true, message: "菜单名称不能为空", trigger: "blur"}
          ],
          component: [
            {required: true, trigger: 'blur', message: '组件名称必须输入'}
          ],
          path: [
            {required: true, message: "路由地址不能为空", trigger: "blur"}
          ]
        }
      }
    },
    created() {
      this.fetchNodeList()
    },
    methods: {
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          pid: 0,
          name: undefined,
          icon: undefined,
          type: 1,
          isOutChain: 0,
          hidden: false,
          status: 1
        };
        this.resetForm("form");
      },
      // 选择图标
      selected(name) {
        this.form.icon = name;
      },
      /** 查询菜单列表 */
      fetchNodeList() {
        this.loading = true;
        menu.getNestedTreeList().then(res => {
          if (res.code === 200) {
            this.menuList = res.data;
            this.loading = false;
          }
        })
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.loading = true;
        menu.getList(this.queryParams).then(res => {
          if (res.code === 200) {
            this.menuList = this.handleTree(res.data, "id");
            this.loading = false;
          }
        }).catch(err => {
          console.log(err);
        })
      },
      /** 转换菜单数据结构 */
      normalizer(node) {
        if (node.children === null) {
          delete node.children;
        }
        return {
          id: node.id,
          label: node.name,
          children: node.children
        };
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 查询菜单下拉树结构 */
      getTreeSelect() {
        menu.getList().then(response => {
          this.menuOptions = [];
          const menu1 = {id: "0", name: '主类目', children: []};
          menu1.children = this.handleTree(response.data, "id");
          this.menuOptions.push(menu1);
        });
      },
      /** 新增按钮操作 */
      handleAdd(row) {
        this.reset();
        this.getTreeSelect();
        if (row != null && row.id) {
          this.form.pid = row.id;
        } else {
          this.form.pid = 0;
        }
        this.open = true;
        this.title = "添加菜单";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        this.getTreeSelect();
        menu.getMenuById(row.id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改菜单";
        });
      },
      /** 提交按钮 */
      submitForm: function () {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id !== undefined) {
              menu.update(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("修改成功");
                  this.open = false;
                  this.fetchNodeList();
                }
              });
            } else {
              menu.save(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.fetchNodeList();
                }
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        this.$confirm('是否确认删除名称为"' + row.name + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return menu.removeById(row.id);
        }).then(() => {
          this.fetchNodeList();
          this.msgSuccess("删除成功");
        }).catch(err => {
          console.log(err);
        });
      },
      statusFormat(row, column) {
        return row.status ? '正常' : '禁用';
      }
    }
  }
</script>
